<template>
    <div class="createPost-container">
        <el-form ref="postForm" :model="postForm" :rules="rules" class="form-container">

            <sticky v-if="!isdetails" :class-name="'sub-navbar '+postForm.status">
                <el-button v-loading="loading" style="margin-left: 10px;" type="primary" @click="submitForm">保存
                </el-button>
            </sticky>

            <div class="createPost-main-container">
                <el-row>
                    <!-- <Warning /> -->
                    <div v-if="isdetails" class="cxcx">
                        <el-button size="medium" type="danger">会议基本信息</el-button>
                    </div>
                    <div v-if="!isdetails" class="cxcxs">
                        <el-button size="medium" type="danger">会议基本信息</el-button>
                    </div>

                    <div>
                        <el-form-item label-width="80px" label="会议名称:" class="postInfo-container-item">
                            <el-input v-if="isdetails" placeholder="请输入内容" v-model="postForm.title" readonly></el-input>
                            <el-input v-if="!isdetails" placeholder="请输入内容" v-model="postForm.title"></el-input>
                        </el-form-item>
                    </div>

                    <div class="postInfo-container">
                        <div class="cxcxcx">
                            <el-form-item label-width="80px" label="开始时间:" class="postInfo-container-item">
                                <el-date-picker v-if="!isdetails" v-model="postForm.display_time" type="datetime" format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期时间" :picker-options="pickerOptions0" />
                                <el-input v-if="isdetails" placeholder="" v-model="postForm.display_time" readonly></el-input>
                            </el-form-item>
                        </div>
                        <div>
                            <el-form-item label-width="80px" label="结束时间:" class="postInfo-container-item">
                                <el-date-picker v-if="!isdetails" v-model="postForm.end_time" type="datetime" format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期时间" :picker-options="pickerOptions1" />
                                <el-input v-if="isdetails" placeholder="" v-model="postForm.end_time" readonly></el-input>
                            </el-form-item>
                        </div>
                        <div>
                            <el-form-item label-width="80px" label="会议地点:" class="postInfo-container-item">
                                <el-input v-if="isdetails" placeholder="请输入内容" v-model="postForm.adrees" readonly></el-input>
                                <el-input v-if="!isdetails" placeholder="请输入内容" v-model="postForm.adrees"></el-input>
                            </el-form-item>
                        </div>
                        <div>
                            <el-form-item label-width="80px" label="报名人数:" class="postInfo-container-item">
                                <el-input v-if="isdetails" placeholder="" v-model="postForm.mannum" readonly></el-input>
                                <el-input v-if="!isdetails" placeholder="请输入内容" v-model="postForm.mannum"></el-input>
                            </el-form-item>
                        </div>
                    </div>
                </el-row>

                <el-form-item style="margin-bottom: 40px;" label-width="80px" label="会议简介:">
                    <el-input :rows="1" v-if="isdetails" v-model="postForm.content_short" type="textarea" class="article-textarea" autosize placeholder="请输入内容" readonly />
                    <span v-show="contentShortLength" class="word-counter">{{ contentShortLength }}字</span>
                    <el-input :rows="1" v-if="!isdetails" v-model="postForm.content_short" type="textarea" class="article-textarea" autosize placeholder="请输入内容" />
                    <span v-show="contentShortLength" class="word-counter">{{ contentShortLength }}字</span>
                </el-form-item>

              <div style="margin: 10px 8px">会议议程:</div>

              <div style="margin-bottom: 8px" v-if="!isdetails">
                <el-input placeholder="请输入议题" style="width: 180px !important" v-model="todolistFormtitle" ></el-input>
                <el-input  placeholder="请输入内容" style="width: 476px !important" v-model="todolistFormcontent" ></el-input>
                <el-input  placeholder="主讲/负责人" style="width: 116px !important" v-model="todolistFormmastor" ></el-input>
                <el-input  type="number" placeholder="时长" style="width: 96px !important" v-model="todolistFormlongTime" ></el-input>
                <el-button @click="addListItem" style="width: 120px !important">添加</el-button>
              </div>
              <el-table  :data="todolist" border fit highlight-current-row style="width:1010px;margin-bottom: 16px;">
                <el-table-column align="center" label="议题" width="180">
                  <template slot-scope="scope">
                    <span>{{ scope.row.title }}</span>
                  </template>
                </el-table-column>

                <el-table-column width="480px" align="center" label="内容">
                  <template slot-scope="scope">
                    <span>{{ scope.row.content }}</span>
                  </template>
                </el-table-column>

                <el-table-column width="120px" align="center" label="主讲/负责人">
                  <template slot-scope="scope">
                    <span>{{ scope.row.mastor }}</span>
                  </template>
                </el-table-column>

                <el-table-column width="100px" label="时长(分钟)">
                  <template slot-scope="scope">
                    <span>{{ scope.row.longTime }}</span>
                  </template>
                </el-table-column>

                <el-table-column align="center" label="Actions" width="128">
                  <template slot-scope="scope">
                    <!--<span v-if="scope.row.edit" type="success" size="small" icon="el-icon-circle-check-outline" @click="confirmEdit(scope.row)">确定</span>-->
                    <!--<span v-else type="primary" size="small" icon="el-icon-edit" @click="scope.row.edit=!scope.row.edit">编辑</span>-->
                    <span v-if="!isdetails" @click="todolist.splice(0,1)">删除</span>

                  </template>
                </el-table-column>

              </el-table>
                <div class="oneCreatePost">
                    <el-upload v-if="!isdetails" class="upload-demo" action="" :auto-upload='false' :on-change='changeUpload'>
                        <el-button size="medium" type="primary">图片上传</el-button>
                        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                    </el-upload>
                </div>
                <!-- <el-button @click="adddefalutList" size="small" type="primary">添加会议邀请信息</el-button> -->
                <el-button v-if="isdetails" size="medium" type="danger">会议图片</el-button>
                <div class="sdsd" v-if="isdetails">
                    <div :key="item.id" v-for="item in postForm.image_uri">
                        <img :src="item.imgUrl" alt="">
                    </div>
                </div>
                <TodoList v-if="!isdetails" @showCityName="submitForms"></TodoList>
                <el-button v-if="isdetails" size="medium" type="danger">会议邀请信息</el-button>
                <TransactionTable :msg='postForm.listNews' v-if="isdetails"></TransactionTable>
            </div>
        </el-form>

    </div>
</template>

<script>
    import Tinymce from '@/components/Tinymce';
    import Upload from '@/components/Upload/singleImage3';
    import MDinput from '@/components/MDinput';
    import Sticky from '@/components/Sticky'; // 粘性header组件
    import { validateURL } from '@/utils/validate';
    import { fetchArticle, upload64, addhuiyi } from '@/api/article';
    import { userSearch } from '@/api/remoteSearch';
    import Warning from './Warning';
    import TodoList from './components/TodoList';
    import TransactionTable from './components/TransactionTable';
    import {
        CommentDropdown,
        PlatformDropdown,
        SourceUrlDropdown
    } from './Dropdown';

    const defaultForm = {
        status: 'draft',
        title: '', // 会议名字
        adrees: '', // 会议地点
        content_short: '', // 会议简介
        source_uri: '', // 文章外链
        image_uri: [], // 会议图片
        display_time: '', // 开始时间
        end_time: '', // 结束时间

        id: undefined,
        platforms: ['a-platform'],
        comment_disabled: false, //是否开启
        mannum: '',
        importance: 0,
        listNews: [
            { title: '姓名', key: '1', done: true },
            { title: '性别', key: '2', done: true }
        ]
    };

    export default {
        name: 'ArticleDetail',
        components: {
            Tinymce,
            MDinput,
            Upload,
            Sticky,
            Warning,
            CommentDropdown,
            PlatformDropdown,
            SourceUrlDropdown,
            TodoList,
            TransactionTable
        },
        props: {
            isEdit: {
                type: Boolean,
                default: false
            }
        },
        data() {
            const validateRequire = (rule, value, callback) => {
                if (value === '') {
                    this.$message({
                        message: rule.field + '为必传项',
                        type: 'error'
                    });
                    callback(new Error(rule.field + '为必传项'));
                } else {
                    callback();
                }
            };
            return {
                postForm: Object.assign({}, defaultForm),
              todolistFormtitle:"",
              todolistFormcontent:"",
              todolistFormmastor:"",
              todolistFormlongTime:"",
                todolist:[

                ],
                loading: false,
                userListOptions: [],
                rules: {
                    title: [{ validator: validateRequire }],
                    content: [{ validator: validateRequire }]
                },
                tempRoute: {},
                defalutList: {},
                listQuery: {
                    status: '2'
                },
                imgurl: {},
                newsdata: null,
                calendarTypeOptions: [
                    { key: '1', display_name: '是' },
                    { key: '2', display_name: '否' }
                ],
                pickerOptions0: {
                    disabledDate: time => {
                        return time.getTime() < Date.now() - 8.64e7;
                    }
                },
                pickerOptions1: {
                    disabledDate: time => {
                        return time.getTime() <= this.postForm.display_time;
                    }
                },
                isdetails: false
            };
        },
        computed: {
            contentShortLength() {
                return this.postForm.content_short.length;
            },
            lang() {
                return this.$store.getters.language;
            }
        },
        created() {
            if (this.isEdit) {
                const id = this.$route.params && this.$route.params.id;
                this.isdetails = true;
                this.fetchData(id);
            } else {
                this.postForm = Object.assign({}, defaultForm);
            }

            // Why need to make a copy of this.$route here?
            // Because if you enter this page and quickly switch tag, may be in the execution of the setTagsViewTitle function, this.$route is no longer pointing to the current page
            // https://github.com/PanJiaChen/vue-element-admin/issues/1221
            this.tempRoute = Object.assign({}, this.$route);
        },
        methods: {
          addListItem(){
            if(!this.todolistFormtitle){
              this.$message({
                message: '请填写会议议程的标题',
                type: 'error'
              })
              return  false;
            }

            this.todolist.push({
              "title":this.todolistFormtitle,
              "content":this.todolistFormcontent,
              "mastor":this.todolistFormmastor,
              "longTime":this.todolistFormlongTime
            });
          },
          setSort() {
            const el = document.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
            this.sortable = Sortable.create(el, {
              ghostClass: 'sortable-ghost', // Class name for the drop placeholder,
              setData: function(dataTransfer) {
                dataTransfer.setData('Text', '')
                // to avoid Firefox bug
                // Detail see : https://github.com/RubaXa/Sortable/issues/1012
              },
              onEnd: evt => {
                const targetRow = this.list.splice(evt.oldIndex, 1)[0]
                this.list.splice(evt.newIndex, 0, targetRow)

                // for show the changes, you can delete in you code
                const tempIndex = this.newList.splice(evt.oldIndex, 1)[0]
                this.newList.splice(evt.newIndex, 0, tempIndex)
              }
            })
          },
          confirmEdit(row) {
            row.edit = false;
            row.originalTitle = row.title
            this.$message({
              message: 'The title has been edited',
              type: 'success'
            })
          },
            fetchData(id) {
                var data = { meetId: id };
                fetchArticle(data).then(msg => {
                    this.postForm.title = msg.data.data.name;
                    this.postForm.adrees = msg.data.data.place;
                    this.postForm.content_short = msg.data.data.remark;
                    this.postForm.display_time = msg.data.data.startTime;
                    this.postForm.end_time = msg.data.data.endTime;
                    this.postForm.image_uri = msg.data.data.imgList;
                    this.postForm.listNews = msg.data.data.invitationFormList;
                    this.postForm.mannum = msg.data.data.num;
                    if(msg.data.data.agenda,length>0){
                      this.todolist = JSON.parse(msg.data.data.agenda)
                    }else{
                      this.todolist = [];
                    }

                });
            },
            setTagsViewTitle() {
                const title = this.lang === 'zh' ? '编辑文章' : 'Edit Article';
                const route = Object.assign({}, this.tempRoute, {
                    title: `${title}-${this.postForm.id}`
                });
                this.$store.dispatch('updateVisitedView', route);
            },
            submitForm() {
                this.$refs.postForm.validate(valid => {
                    if (valid) {
                        this.loading = true;
                        var data = {
                            name: this.postForm.title,
                            startTime: this.postForm.display_time,
                            endTime: this.postForm.end_time,
                            place: this.postForm.adrees,
                            num: this.postForm.mannum || 9999,
                            remark: this.postForm.content_short,
                            imgList: this.postForm.image_uri,
                            invitationFormList: this.postForm.listNews,
                            agenda: JSON.stringify(this.todolist)
                        };
                        if (data.name.length == 0) {
                            this.$message({
                                message: '会议名称不能为空',
                                type: 'error'
                            });
                        }
                        if (data.startTime.length == 0) {
                            this.$message({
                                message: '开始时间不能为空',
                                type: 'error'
                            });
                            this.loading = false;
                        } else if (data.endTime.length == 0) {
                            this.$message({
                                message: '结束时间不能为空',
                                type: 'error'
                            });
                            this.loading = false;
                        } else if (data.place.length == 0) {
                            this.$message({
                                message: '会议地点不能为空',
                                type: 'error'
                            });
                            this.loading = false;
                        } else if (Number(data.num) <= 0) {
                            this.$message({
                                message: '报名人数不能为负数',
                                type: 'error'
                            });
                            this.loading = false;
                        } else {
                            if (data.imgList.length < 2) {
                                data.imgList.push(
                                    {
                                        imgUrl:
                                            'http://main.zlsoft.net.cn/bgimg/img3.png'
                                    },
                                    {
                                        imgUrl:
                                            'http://main.zlsoft.net.cn/bgimg/img1.png'
                                    }
                                );
                                this.loading = false;
                            }

                            data.startTime = data.startTime.getTime();
                            data.endTime = data.endTime.getTime();
                            addhuiyi(data).then(res => {
                                console.log(res);
                                this.postForm.status = 'published';
                                this.loading = false;
                                this.$notify({
                                    title: '成功',
                                    message: '保存成功',
                                    type: 'success',
                                    duration: 2000
                                });
                                this.$router.push({
                                    path: this.redirect || '/example/list'
                                });
                            });
                        }
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            submitForms(data) {
                this.postForm.listNews = [];
                if (data.length > 0) {
                    data.map((value, index) => {
                        if (value.done) {
                            this.postForm.listNews.push(value);
                        }
                    });
                } else {
                    this.postForm.listNews = [];
                }
                console.log('父', data);
            },
            draftForm() {
                if (
                    this.postForm.content.length === 0 ||
                    this.postForm.title.length === 0
                ) {
                    this.$message({
                        message: '请填写必要的标题和内容',
                        type: 'warning'
                    });
                    return;
                }
                this.$message({
                    message: '保存成功',
                    type: 'success',
                    showClose: true,
                    duration: 1000
                });
                this.postForm.status = 'draft';
            },
            getRemoteUserList(query) {
                userSearch(query).then(response => {
                    if (!response.data.items) return;
                    this.userListOptions = response.data.items.map(v => v.name);
                });
            },
            changeUpload: function(file, fileList) {
                var _thiss = this;
                this.fileList = fileList;
                this.$nextTick(() => {
                    let upload_list_li = document.getElementsByClassName(
                        'el-upload-list'
                    )[0].children;
                    for (let i = 0; i < upload_list_li.length; i++) {
                        let li_a = upload_list_li[i];
                        let imgElement = document.createElement('img');
                        imgElement.setAttribute('src', fileList[i].url);
                        imgElement.setAttribute(
                            'style',
                            'max-width:50%;padding-left:25%'
                        );
                        if (li_a.lastElementChild.nodeName !== 'IMG') {
                            li_a.appendChild(imgElement);
                        }
                    }
                });
                const reader = new FileReader();
                reader.readAsDataURL(file.raw);
                reader.onload = function(e) {
                    var _this = this;
                    this.result; // 这个就是base64编码了
                    const data = {
                        file: _this.result
                    };
                    upload64(data).then(msg => {
                        if (msg.data.code == 1) {
                            _thiss.imgurl = { imgUrl: msg.data.data.fullPath };
                            _thiss.postForm.image_uri.push(_thiss.imgurl);
                        }
                    });
                };
            },
            adddefalutList() {
                this.defalutList = { text: '', done: true };
                console.log(this.defalutList);
            }
        }
    };
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
    @import 'src/styles/mixin.scss';
    .createPost-container {
        position: relative;
        .createPost-main-container {
            padding: 40px 45px 20px 50px;
            .postInfo-container {
                position: relative;
                @include clearfix;
                margin-bottom: 10px;
                .postInfo-container-item {
                    float: left;
                }
            }
            .editor-container {
                min-height: 500px;
                margin: 0 0 30px;
                .editor-upload-btn-container {
                    text-align: right;
                    margin-right: 10px;
                    .editor-upload-btn {
                        display: inline-block;
                    }
                }
            }
        }
        .word-counter {
            width: 40px;
            position: absolute;
            right: -10px;
            top: 0px;
        }
    }
    .cxcx {
        position: relative;
        top: -20px;
    }
    .cxcxs {
        position: relative;
        top: -20px;
    }
    .sdsd {
        margin-bottom: 20px;
        padding-top: 20px;
    }
    .el-form-item {
        float: inherit !important;
        width: 50% !important;
    }
    .el-form-item__content {
        width: 100% !important;
    }
    .el-input--medium {
        width: 100% !important;
    }
    .sdsd {
        width: 400px;
        img {
            max-width: 100%;
            height: auto;
        }
    }
</style>
